﻿using System.Configuration;
using System.Dynamic;

namespace SBToolkit.Configuration
{
    /// <summary>
    /// Simplified way to access configuration files.
    /// </summary>
    public class Config : DynamicObject
    {
        /// <summary>
        /// Static configuration instance.
        /// </summary>
        private static readonly Config config = new Config();

        /// <summary>
        /// Current configuration.
        /// </summary>
        public static dynamic Current
        {
            get
            {
                return config;
            }
        }

        /// <summary> 
        /// Provides the implementation of getting a member.  Derived classes can override
        /// this method to customize behavior.  When not overridden the call site requesting the 
        /// binder determines the behavior. 
        /// </summary>
        /// <param name="binder">The binder provided by the call site.</param> 
        /// <param name="result">The result of the get operation.</param>
        /// <returns><c>True</c> if the operation is complete, <c>false</c> if the call site should determine behavior.</returns>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = ConfigurationManager.AppSettings[binder.Name];

            if (result == null && ConfigurationManager.ConnectionStrings[binder.Name] != null)
            {
                result = ConfigurationManager.ConnectionStrings[binder.Name].ConnectionString;
            }

            return result != null;
        }
    }
}
